import {View} from '@ant-design/react-native';
import {ScrollView} from 'react-native';
import React, {useEffect, useState} from 'react';
import ChatBoxLeft from '../../../component/chatBox/ChatBoxLeft';
import ChatBoxRight from '../../../component/chatBox/ChatBoxRight';
import InputButton from '../../../component/InputButton';
import axios, {websocketUrl} from '../../../http/http';
import useStorage from '../../../hooks/storage';
import {TUserInfo} from '../../../type/TUser';
import {TChatRoom} from '../../../type/TChatRoom';
import {StyleSheet} from 'react-native';
const ChatRoom = () => {
  useEffect(() => {
    getChatRoomList();
    getUserInfo();
  }, []);
  const [chatRoomList, setChatRoomList] = useState<TChatRoom[]>([]);
  const [value, setValue] = useState<string>('');
  const [ws, setWs] = useState<WebSocket | null>(null);
  let userInfo: TUserInfo | null = null;
  const getChatRoomList = () => {
    axios.get('/chatRoom/search').then(res => {
      setChatRoomList(res.data);
    });
  };
  const userInfoStorage = useStorage<TUserInfo>('userInfo');
  const getUserInfo = async () => {
    userInfo = await userInfoStorage.getItem();
  };
  const sendMessage = () => {
    console.log(value);
  };
  const connectWebSocket = () => {
    const ws = new WebSocket(`${websocketUrl}/socketRoom/${userInfo!.id}`);
  };
  return (
    <>
      <ScrollView style={styles.ChatRoomPlan}>
        <View>
          {chatRoomList.length &&
            chatRoomList.map(item =>
              item.userId === userInfo?.id ? (
                <View style={{marginBottom: 10}}>
                  <ChatBoxRight
                    content={item.message}
                    realname={item.realname}
                  />
                </View>
              ) : (
                <View style={{marginBottom: 10}}>
                  <ChatBoxLeft
                    content={item.message}
                    realname={item.realname}
                  />
                </View>
              ),
            )}
        </View>
      </ScrollView>
      <InputButton
        value={value}
        type="text"
        onChange={setValue}
        valid={sendMessage}
      />
    </>
  );
};
const styles = StyleSheet.create({
  ChatRoomPlan: {
    paddingHorizontal: 16,
  },
});
export default ChatRoom;
